package gov.kqqzyyy.monkey.orderpad.mytools;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by Monkey on 2017/4/20.
 * 网络信息相关
 */

public class NetWorkUtil {

    public static String IPV4_ADD;
    public static String MAC_ADD;

    /**
     * 获取IPV4地址
     */
    public static void getNetInfo() {
        String ipaddress;
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                if (intf.getName().toLowerCase().equals("eth0") || intf.getName().toLowerCase().equals("wlan0")) {
                    for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        if (!inetAddress.isLoopbackAddress()) {
                            ipaddress = inetAddress.getHostAddress();
                            if (!ipaddress.contains("::")) {//非ipV6的地址
                                IPV4_ADD = ipaddress;
                                MAC_ADD = changeToMac(intf.getHardwareAddress());
                            }
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    /**
     * 转mac地址格式
     */
    private static String changeToMac(byte[] bytes) {
        StringBuilder buf = new StringBuilder();
        for (byte b : bytes) {
            buf.append(String.format("%02X:", b));
        }
        if (buf.length() > 0) {
            buf.deleteCharAt(buf.length() - 1);
        }
        return buf.toString();
    }

}
